/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: ProcessSZXZ
 * Author:   ThinkPad
 * Date:     2020/6/24 17:08
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.jt.www.queue.process;

import com.jt.www.enums.issue.IssueEnum;
import com.jt.www.enums.issue.PolicyInterfaceEnum;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.util.DateUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author xq.wu
 * @Description 实责校责（太平）
 * 实责校责（中华联合）
 * 实责校责 新国寿财
 * @create 2020/6/24
 * @since 1.0.0
 */
@Service
public class ProcessSZXZ extends ElecPolicyProcess implements InitializingBean {

    public static final Logger log = LoggerFactory.getLogger(ProcessSZXZ.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_22.getIfCode(), this);
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_23.getIfCode(), this);
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_24.getIfCode(), this);
    }

    @Override
    public Boolean process(Element rootElement, String ifCode) {
        Element respPacket = getRespPacket(rootElement);
        Element reqPacket = getReqPacket(rootElement);

        String currentTime = DateUtils.getCurrentTime();

        List<Element> respChildElements = respPacket.element("Body").elements();
        String status = null;
        String tbNo = null;
        String policyNo = null;
        for (Element child : respChildElements) {
            //0：成功  其余：失败
            if (ifCode.equals("20190731001")) {
                status = respPacket.element("Head").element("Code").getStringValue();
                tbNo = child.element("AppCode").getStringValue();
                // 保单号
                policyNo = child.element("PolicyCode").getStringValue();
            } else {
                status = respPacket.element("Head").element("ResponseCode").getStringValue();
                // 投保单号
                tbNo = child.element("ApplyId").getStringValue();
                // 保单号
                policyNo = child.element("PolicyNo").getStringValue();
            }
            // 解析险种
            List<Element> reqChildElements = reqPacket.element("Body").elements();
            String proCode = "";
            String mainType = "";
            for (Element reqChild : reqChildElements) {
                String applyId = reqChild.element("ApplyId").getStringValue();
                if (tbNo.equals(applyId)) {
                    mainType = reqChild.element("MainType").getStringValue();
                    proCode = IssueEnum.getProCodeByIfCode(ifCode + mainType);
                    break;
                }
            }

            log.debug("系统时间：{}, [实责校责]下载电子保单 投保单号：{},保单号：{},产品险种编码：{}", currentTime, tbNo, policyNo, proCode);
            // 入库
            // 入库之前首先判断 是否已经入库  根据投保单号判断
            if (judgingStorage(tbNo)) {
                return true;
            }
            IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
            issueRecordEntity.setApplicationFormCode(tbNo);

            issueRecordEntity.setPolicyNo(policyNo);
            issueRecordEntity.setProCode(proCode);
            issueRecordEntity.setMainType(mainType);
            issueRecordEntity.setReqPacket(reqPacket.asXML());
            issueRecordEntity.setResPacket(respPacket.asXML());
            issueRecordEntity.setSendStatus("1");

            //0：成功  其余：失败
            if ("0".equals(status)) {
                status = "2";
            } else {
                status = "3";
            }
            // 数据中心返回 的投保单状态
            issueRecordEntity.setStatus(status);
            issueRecordEntity.setCreateTime(currentTime);
            issueRecordEntity.setUpdateTime(currentTime);
            issueRecordEntity.setIfCode(ifCode);
            issueRecordEntityMapper.insert(issueRecordEntity);
            if ("3".equals(status)) {
                // 出单失败或者重复出单，消息直接消费完成，在入库的逻辑后边。
                break;
            }
            // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
            IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
            String consumeStatus = "1";
            issuePolicyLogEntity.setApplicationFormCode(tbNo);
            issuePolicyLogEntity.setPolicyNo(policyNo);
            issuePolicyLogEntity.setType("1");
            issuePolicyLogEntity.setStatus(consumeStatus);
            issuePolicyLogEntity.setCreateTime(currentTime);
            issuePolicyLogEntity.setUpdateTime(currentTime);
            issuePolicyLogEntity.setMainType(mainType);
            issuePolicyLogEntity.setProCode(proCode);

            // 拼装下载报文
            Document doc = DocumentHelper.createDocument();
            Element info = null;
            if (ifCode.equals("20190827001")) {
                info = DocumentHelper.createElement("EduApply");
                doc = DocumentHelper.createDocument(info);
                Element head = info.addElement("head");
                Element userId = head.addElement("UserId"); //
                userId.setText("100000");
                Element commandId = head.addElement("CommandId");
                commandId.setText("ERA0001");
                Element seqNo = head.addElement("SeqNo");
                seqNo.setText(tbNo);
                Element body = info.addElement("BODY");
                Element policyNoOn = body.addElement("PolicyNo");
                policyNoOn.setText(policyNo);
            } else {
                String policyUrl = child.element("PolicyUrl").getStringValue();
                info = doc.addElement("body");
                info.addElement("url").addText(policyUrl);
            }

            //info.addElement("url").addText("https://iepolicy.sinosig.com/digitalBill_download/downloadPolicy.action?file=201908211045-247a5479-9f32-4036-943c-f55c052a73c9");


            issuePolicyLogEntity.setParam(info.asXML());
            issuePolicyLogEntity.setTimes(0);
            issuePolicyLogEntity.setIfCode(ifCode);
            issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
            // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
            issueRecordEntity.setSendStatus("2");
            issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
            String eUrl = null;
            //调用接口,请求数据交换中心，下载电子保单
            try {
                //国寿财电子保单需要特殊处理
                if (ifCode.equals("20190827001")) {
                    eUrl = doc.asXML();
                } else {
                    eUrl = info.asXML().replace("&amp;", "&");
                }
                log.info("实责校责的投保单号是: {}, 保单下载参数：{}", tbNo, eUrl);
                // 请求下载保单，成功更新
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                ResponseEntity<String> responseEntity = null;
                if (ifCode.equals("20190827001")) {
                    responseEntity = dexClient.text("edu", "20191118001", "1.0", seqNo, eUrl);
                } else {
                    responseEntity = dexClient.text("edu", "20190726008", "1.0", seqNo, eUrl);

                }
                String ebody = responseEntity.getBody();
                log.info("实责校责的投保单号是: {}, 保单下载返回值：{}, {}", tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());

                consumeStatus = "2";
                if (ebody == null) {
                    log.error("实责校责请求下载电子保单失败");
                    consumeStatus = "3";
                }
                if (ifCode.equals("20190827001")) {
                    Document resultDoc = DocumentHelper.createDocument();
                    resultDoc = DocumentHelper.parseText(ebody);
                    Element ebodyElement = resultDoc.getRootElement();
                    Element data = ebodyElement.element("data");
                    ebody = data.getStringValue();
                }
                issuePolicyLogEntity.setStatus(consumeStatus);
                // 下载成功，更新数据库，绑定资源
                log.info("实责校责的投保单号是  下载消息 fileId：{}", ebody);
                bindingResources(tbNo, ebody, issuePolicyLogEntity);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            sendEmail(tbNo, "21");
        }

        return true;
    }


}